import { subList, delSub } from '@/services/ant-design-pro/source';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, Input, message } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { history } from '@umijs/max';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  // const { run: delRun, loading } = useRequest(removeRule, {
  //   manual: true,
  //   onSuccess: () => {
  //     setSelectedRows([]);
  //     actionRef.current?.reloadAndRest?.();
  //     messageApi.success('Deleted successfully and will refresh soon');
  //   },
  //   onError: () => {
  //     messageApi.error('Delete failed, please try again');
  //   },
  // });
  const handleRemove = async (data:any) =>{
    const res = await delSub({id: data.id})
    if(res.code === 0){
      messageApi.success('删除成功')
      actionRef.current?.reload()
    }else{
      messageApi.error('删除失败')
    }
  }
  const  handleNavTo = (data: any) =>{
    const idArray = {typeId: data.id, typeName: data.name};
    localStorage.setItem('idArray', JSON.stringify(idArray))
    history.push('/list/category-list/classify-list',idArray)
  }

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title:'学科',
      dataIndex: 'name',
      tip: 'The rule name is the unique key',
      render: (dom, entity) => {
        return (
          <a>
            {dom}
          </a>
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      sorter: true,
      hideInForm: true,
      renderText: (val: string) =>`${val}`,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Button type="link" onClick={()=>handleNavTo(record)}>资源</Button>,
        <UpdateForm
          trigger={
            <Button type="link">编辑</Button>
          }
          key="config"
          onOk={actionRef.current?.reload}
          values={record}
        />,
        <Button type="link" onClick={()=>handleRemove(record)} danger>删除</Button>,
      ],
    },
  ];

  // /**
  //  *  Delete nodedanger
  //  * @zh-CN 删除节点
  //  *
  //  * @param selectedRows
  //  */
  // const handleRemove = useCallback(
  //   async (selectedRows: API.RuleListItem[]) => {
  //     if (!selectedRows?.length) {
  //       messageApi.warning('请选择删除项');

  //       return;
  //     }

  //     await delRun({
  //       data: {
  //         key: selectedRows.map((row) => row.key),
  //       },
  //     });
  //   },
  //   [delRun],
  // );

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolBarRender={() => [<CreateForm key="create" reload={actionRef.current?.reload} />]}
        request={async (params:{
          pageSize: number;
          current: number;
        })=>{
          const msg = await subList({
            pageNo: params.current -1,
            pageSize: params.pageSize,
          })
          return {
            data:msg.obj.list,
            success:msg.obj.total,
          }
        }}
        columns={columns}
        rowSelection={false}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
